import { createSignal, createEffect } from 'solid-js';
import { Collection, CreateCollectionParams } from '@/types/collection';
import { saveTextFile, readTextFile } from '@/lib/api/file';

const COLLECTIONS_FILE = 'collections.json';
const [collections, setCollections] = createSignal<Collection[]>([]);
const [initialized, setInitialized] = createSignal(false);

async function initCollections() {
  try {
    const data = await readTextFile(COLLECTIONS_FILE);
    const parsedData = JSON.parse(data);
    if (Array.isArray(parsedData)) {
      setCollections(parsedData);
    }
  } catch (error) {
    console.error('Failed to load collections:', error);
    // 如果文件不存在，使用空数组，但不会覆盖已有文件
  } finally {
    setInitialized(true);
  }
}

createEffect(() => {
  // 只有在初始化完成后才开始自动保存
  if (initialized()) {
    const currentCollections = collections();
    saveTextFile(COLLECTIONS_FILE, JSON.stringify(currentCollections))
      .catch(error => console.error('Failed to save collections:', error));
  }
});

export const useCollectionStore = () => {
  const addCollection = (params: CreateCollectionParams): Collection => {
    const newCollection: Collection = {
      id: Date.now().toString(),
      name: params.name,
      description: params.description,
      apps: [],
      createdAt: Date.now(),
      updatedAt: Date.now(),
    };
    setCollections([...collections(), newCollection]);
    return newCollection;
  };

  const addAppToCollections = (collectionIds: string[], Category: string, Pkgname: string) => {
    setCollections(prev => prev.map(collection => {
      if (collectionIds.includes(collection.id)) {
        const appExists = collection.apps.some(app => 
          app.Category === Category && app.Pkgname === Pkgname
        );
        if (!appExists) {
          return {
            ...collection,
            apps: [...collection.apps, { Category, Pkgname }],
            updatedAt: Date.now(),
          };
        }
      }
      return collection;
    }));
  };

  const removeAppFromCollection = (collectionId: string, Category: string, Pkgname: string) => {
    setCollections(prev => prev.map(collection => {
      if (collection.id === collectionId) {
        return {
          ...collection,
          apps: collection.apps.filter(app => 
            !(app.Category === Category && app.Pkgname === Pkgname)
          ),
          updatedAt: Date.now(),
        };
      }
      return collection;
    }));
  };

  const isAppInCollection = (collectionId: string, Category: string, Pkgname: string): boolean => {
    const collection = collections().find(c => c.id === collectionId);
    return collection?.apps.some(app => app.Category === Category && app.Pkgname === Pkgname) || false;
  };

  return {
    collections,
    addCollection,
    addAppToCollections,
    removeAppFromCollection,
    isAppInCollection,
  };
};

// 初始化收藏单数据
initCollections();